package suanfa;

//顺时针打印矩阵
public class offer20 {
/*   1 2 3 4
     4 3 2 1
     8 6 7 5   1 endrow 5-1-1=3 2
     6 3 5 8
     5 4 7 2
     顺时针打印矩阵*/


    public static void main(String[] args) {
        //int a[][] = {{1, 2, 3, 4}, {4, 3, 2, 1}, {8, 6, 7, 5}, {6, 3, 5, 8}, {5, 4, 7, 2}};
        int a[][]={{1,2},{3,4}};
        PrintAll(a, a[0].length, a.length);//参数:数组，列数，行数

    }

    public static void PrintAll(int[][] numbers, int cols, int rows) {//col为列数 row为行数
        if (numbers == null || cols <= 0 || rows <= 0)
            return;
        int start = 0;
        while (cols > start * 2 && rows > start * 2) {
            Print(numbers, cols, rows, start);
            start++;
        }
    }

    public static void Print(int[][] numbers, int cols, int rows, int start) {
        int endCols = cols - 1 - start;
        int endRows = rows - 1 - start;
        for (int i = start; i <= endCols; ++i) {
            System.out.print(numbers[start][i] + " ");
        }
        //这里以后的三次循环都要做判断 因为每次做完一行或一列遍历 可能矩阵已经全部遍历完
        // (ps:为什么第一次不做判断？因为在方法开始前已经做了判断)
        if (start < endRows) {
            for (int i = start + 1; i <= endRows; ++i) {
                System.out.print(numbers[i][endCols] + " ");
            }
            if (start < endCols) {
                for (int i = endCols - 1; i >= start; --i) {
                    System.out.print(numbers[endRows][i] + " ");
                }
                if (start < endRows - 1) {
                    for (int i = endRows - 1; i >= start + 1; --i) {
                        System.out.print(numbers[i][start] + " ");
                    }
                }
            }
        }
    }
}
